class Enlarge {
    constructor (select) {
      this.ele = document.querySelector(select)
      this.show = this.ele.querySelector('.enlarge .top')
      this.mask = this.ele.querySelector('.mask')
      this.list = this.ele.querySelector('.list')
      this.enlarge = this.ele.querySelector('.enlargebox')
      this.show_width = this.show.clientWidth
      this.show_height = this.show.clientHeight
      this.mask_width = parseInt(window.getComputedStyle(this.mask).width)
      this.mask_height = parseInt(window.getComputedStyle(this.mask).height)
      this.bg_width = parseInt(window.getComputedStyle(this.enlarge.firstElementChild).width)
      this.bg_height = parseInt(window.getComputedStyle(this.enlarge.firstElementChild).height)
      this.setScale()
      this.overOut()
      this.changeImg()
      this.move()
    }
  
    setScale () {
      this.enlarge_width = this.mask_width * this.bg_width / this.show_width
      this.enlarge_height = this.mask_height * this.bg_height / this.show_height
      this.enlarge.style.width = this.enlarge_width + 'px'
      this.enlarge.style.height = this.enlarge_height + 'px'
    }
  
    changeImg () {
      this.list.addEventListener('click', e => {
        if (e.target.nodeName !== 'IMG') return
        for (let i = 0; i < this.list.children.length; i++) {
          this.list.children[i].classList.remove('active')
        }
        e.target.classList.add('active')
        const show_url = e.target.dataset.show
        const enlarge_url = e.target.dataset.enlarge
        this.show.firstElementChild.src = show_url
        this.enlarge.firstElementChild.src = enlarge_url
      })
    }
  
    overOut () {
      this.show.addEventListener('mouseover', () => {
        this.mask.style.display = 'block'
        this.enlarge.style.display = 'block'
      })
      this.show.addEventListener('mouseout', () => {
        this.mask.style.display = 'none'
        this.enlarge.style.display = 'none'
      })
    }
  
    move () {
      this.show.addEventListener('mousemove', e => {
        let x = e.offsetX - this.mask_width / 2
        let y = e.offsetY - this.mask_height / 2
        if (x <= 0) x = 0
        if (y <= 0) y = 0
        if (x >= this.show_width - this.mask_width) x = this.show_width - this.mask_width
        if (y >= this.show_height - this.mask_height) y = this.show_height - this.mask_height
        this.mask.style.left = x + 'px'
        this.mask.style.top = y + 'px'
  
        const bg_x = x * this.enlarge_width / this.mask_width
        const bg_y = y * this.enlarge_height / this.mask_height
        
        this.enlarge.firstElementChild.style.left = -bg_x + 'px'
        this.enlarge.firstElementChild.style.top = -bg_y + 'px'
      })
    }
  }